package org.adream.account.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFDataFormat;
import org.apache.poi.xssf.usermodel.XSSFDataValidation;
import org.apache.poi.xssf.usermodel.XSSFDataValidationConstraint;
import org.apache.poi.xssf.usermodel.XSSFDataValidationHelper;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * excel导出工具类
 * @author Administrator
 *
 */
public class ExportExcelUtil {

	private static final Logger logger = LoggerFactory.getLogger(ExportExcelUtil.class);

	/**
	 * 导出Excel
	 * 
	 * @param excelName
	 *            要导出的excel名称
	 * @param list
	 *            要导出的数据集合
	 * @param fieldMap
	 *            中英文字段对应Map,即要导出的excel表头
	 * @param response
	 *            使用response可以导出到浏览器
	 * @return
	 */
	public static <T> void export(String excelName, String sheetName, List<T> list, LinkedHashMap<String, String> fieldMap, HttpServletResponse response) {
		// 设置默认文件名为当前时间：年月日时分秒
		if (excelName == null || excelName == "") {
			excelName = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date()).toString();
		}
		// 设置response头信息
		response.reset();
		response.setContentType("application/vnd.ms-excel"); // 改成输出excel文件
		try {
			response.setHeader("Content-disposition",
					"attachment; filename=" + new String(excelName.getBytes("UTF-8"), "ISO-8859-1") + ".xls");
		} catch (UnsupportedEncodingException e1) {
			logger.info(e1.getMessage());
		}
		OutputStream out = null;
		try {
			// 创建一个WorkBook,对应一个Excel文件
			XSSFWorkbook wb = new XSSFWorkbook();
			// 在Workbook中,创建一个sheet,对应Excel中的工作薄(sheet)
			XSSFSheet sheet = wb.createSheet(sheetName);
			// 创建单元格,并设置值表头 设置表头居中
			XSSFCellStyle style = wb.createCellStyle();
			// 创建一个居中格式
			//style.setAlignment(XSSFCellStyle.ALIGN_CENTER);
			style.setAlignment(HorizontalAlignment.CENTER);
			XSSFDataFormat format = wb.createDataFormat();
			// 填充工作表
			fillSheet(sheet, list, fieldMap, style, format);
			// 将文件输出
			out = response.getOutputStream();
			wb.write(out);
			out.flush();
		} catch (Exception e) {
			logger.error("导出Excel失败:" + e.getMessage());
		} finally {
			if(out != null) {
				try {
					out.close();
				} catch (IOException e) {
					logger.warn("导出Excel失败:" + e.getMessage());
				}
			}
		}
	}
	
	/**
	 * 导出excel
	 * @param excelName		excel名称
	 * @param wb			
	 * @param response
	 */
	public static void export(String excelName, XSSFWorkbook wb, HttpServletResponse response) {
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		OutputStream out = null;
		try {
			wb.write(os);
			byte[] bytes = os.toByteArray();
			response.reset();
			response.setContentType("application/vnd.ms-excel;charset=utf-8");
			response.setHeader("Content-disposition", "attachment;filename= " + new String(excelName.getBytes("UTF-8"), "ISO-8859-1") + ".xlsx");
			out = response.getOutputStream();
			out.write(bytes);
			out.flush();
		} catch (IOException e) {
			logger.error("导出excel失败:{}", e.getMessage());
		} finally {
			if(out != null) {
				try {
					out.close();
				} catch (IOException e) {
					logger.error("导出excel失败:{}", e.getMessage());
				}
			}
			if(os != null) {
				try {
					os.close();
				} catch (IOException e) {
					logger.error("导出excel失败:{}", e.getMessage());
				}
			}
		}
	}
	
	/**
	 * 导出excel
	 * @param excelName		excel名称
	 * @param wb			
	 * @param response
	 */
	public static void export(String excelName, Workbook wb, HttpServletResponse response) {
		// 设置response头信息
		response.reset();
		response.setContentType("application/vnd.ms-excel"); // 改成输出excel文件
		try {
			response.setHeader("Content-disposition",
					"attachment; filename=" + new String(excelName.getBytes("UTF-8"), "ISO-8859-1") + ".xlsx");
		} catch (UnsupportedEncodingException e1) {
			logger.info(e1.getMessage());
		}
		OutputStream out = null;
		try {
			// 将文件输出
			out = response.getOutputStream();
			wb.write(out);
			out.flush();
		} catch (Exception e) {
			logger.error("导出Excel失败:" + e.getMessage());
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					logger.warn("导出Excel失败:" + e.getMessage());
				}
			}
		}
	}

	/**
	 * 根据字段名获取字段对象
	 *
	 * @param fieldName
	 *            字段名
	 * @param clazz
	 *            包含该字段的类
	 * @return 字段
	 */
	public static Field getFieldByName(String fieldName, Class<?> clazz) {
		// 获取类的所有字段
		Field[] selfFields = clazz.getDeclaredFields();
		// 如果本类中存在该字段,则返回
		for (Field field : selfFields) {
			// 如果本类中存在该字段,则返回
			if (field.getName().equals(fieldName)) {
				return field;
			}
		}
		// 否则,查看父类中是否存在此字段,如果有则返回
		Class<?> superClazz = clazz.getSuperclass();
		if (superClazz != null && superClazz != Object.class) {
			// 递归
			return getFieldByName(fieldName, superClazz);
		}
		// 如果本类和父类都没有,则返回空
		return null;
	}

	/**
	 * 根据字段名获取字段值
	 *
	 * @param fieldName
	 *            字段名
	 * @param o
	 *            对象
	 * @return 字段值
	 * @throws Exception
	 *             异常
	 * 
	 */
	public static Object getFieldValueByName(String fieldName, Object o) throws Exception {
		Object value = null;
		// 根据字段名得到字段对象
		Field field = getFieldByName(fieldName, o.getClass());

		// 如果该字段存在,则取出该字段的值
		if (field != null) {
			field.setAccessible(true);// 类中的成员变量为private,在类外边使用属性值,故必须进行此操作
			value = field.get(o);// 获取当前对象中当前Field的value
		} else {
			throw new Exception(o.getClass().getSimpleName() + "类不存在字段名 " + fieldName);
		}
		return value;
	}

	/**
	 * 根据带路径或不带路径的属性名获取属性值,即接受简单属性名,
	 * 如userName等,又接受带路径的属性名,如student.department.name等
	 *
	 * @param fieldNameSequence
	 *            带路径的属性名或简单属性名
	 * @param o
	 *            对象
	 * @return 属性值
	 * @throws Exception
	 *             异常
	 * 
	 */
	public static Object getFieldValueByNameSequence(String fieldNameSequence, Object o) throws Exception {
		Object value = null;
		// 将fieldNameSequence进行拆分
		String[] attributes = fieldNameSequence.split("\\.");
		if (attributes.length == 1) {
			value = getFieldValueByName(fieldNameSequence, o);
		} else {
			// 根据数组中第一个连接属性名获取连接属性对象,如student.department.name
			Object fieldObj = getFieldValueByName(attributes[0], o);
			// 截取除第一个属性名之后的路径
			String subFieldNameSequence = fieldNameSequence.substring(fieldNameSequence.indexOf(".") + 1);
			// 递归得到最终的属性对象的值
			value = getFieldValueByNameSequence(subFieldNameSequence, fieldObj);
		}
		return value;
	}

	/**
	 * 向工作表中填充数据
	 *
	 * @param sheet
	 *            excel的工作表名称
	 * @param list
	 *            数据源
	 * @param fieldMap
	 *            中英文字段对应关系的Map
	 * @param style
	 *            表格中的格式
	 * @throws Exception
	 *             异常
	 * 
	 */
	public static <T> void fillSheet(XSSFSheet sheet, List<T> list, LinkedHashMap<String, String> fieldMap, XSSFCellStyle style, XSSFDataFormat format) throws Exception {
		logger.info("向工作表中填充数据:fillSheet()");
		// 定义存放英文字段名和中文字段名的数组
		String[] enFields = new String[fieldMap.size()];
		String[] cnFields = new String[fieldMap.size()];

		// 填充数组
		int count = 0;
		for (Entry<String, String> entry : fieldMap.entrySet()) {
			enFields[count] = entry.getKey();
			cnFields[count] = entry.getValue();
			count++;
		}

		// 在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
		XSSFRow row = sheet.createRow((int) 0);

		// 填充表头
		for (int i = 0; i < cnFields.length; i++) {
			XSSFCell cell = row.createCell(i);
			cell.setCellValue(cnFields[i]);
			cell.setCellStyle(style);
			sheet.setColumnWidth(i, cnFields[i].length() * 800);
		}

		// 填充内容
		for (int index = 0; index < list.size(); index++) {
			row = sheet.createRow(index + 1);
			// 获取单个对象
			T item = list.get(index);
			for (int i = 0; i < enFields.length; i++) {
				Object objValue = getFieldValueByNameSequence(enFields[i], item);
				String fieldValue = "";
				if(objValue != null) {
					fieldValue = "";
					if(objValue instanceof Date) {
						fieldValue = DateUtils.parseDateString(String.valueOf(objValue), "yyyy-MM-dd HH:mm:ss");						
					} else {
						//若字段为state时,格式化state,设置下拉选框
						if("state".equals(enFields[i])) {
							fieldValue = formatState(Integer.parseInt((String) objValue));
							//设置认证状态那列为下拉选框
							String[] state = {"审核中","审核成功","审核失败"};
							XSSFDataValidationHelper dvHelper = new XSSFDataValidationHelper(sheet);
					        XSSFDataValidationConstraint dvConstraint1 = (XSSFDataValidationConstraint) dvHelper.createExplicitListConstraint(state);
					        CellRangeAddressList addressList = new CellRangeAddressList(1, list.size(), i,i);
					        XSSFDataValidation dataValidation = (XSSFDataValidation) dvHelper.createValidation(dvConstraint1,addressList);
					        sheet.addValidationData(dataValidation);
						} else {
							//反转义HTML
							fieldValue = StringEscapeUtils.unescapeHtml(objValue.toString());
						}
					}
				}
				row.setZeroHeight(false);
				row.setHeight((short) 1000);
				XSSFCell cell = row.createCell(i);
				//设置单元格格式为文本格式
				style.setDataFormat(format.getFormat("@"));
				cell.setCellStyle(style);
				//cell.setCellType(XSSFCell.CELL_TYPE_STRING);
				cell.setCellType(CellType.STRING);
				cell.setCellValue(fieldValue);
			}
		}		
	}
	
	/**
	 * 向工作表中填充数据
	 *
	 * @param sheet
	 *            excel的工作表名称
	 * @param list
	 *            数据源
	 * @param fieldMap
	 *            中英文字段对应关系的Map
	 * @param style
	 *            表格中的格式
	 * @throws Exception
	 *             异常
	 * 
	 */
	public static <T> void fillSXSSFSheet(Sheet sheet, List<T> list, LinkedHashMap<String, String> fieldMap, CellStyle style, DataFormat format) throws Exception {
		logger.info("向工作表中填充数据:fillSheet()");
		// 定义存放英文字段名和中文字段名的数组
		String[] enFields = new String[fieldMap.size()];
		String[] cnFields = new String[fieldMap.size()];

		// 填充数组
		int count = 0;
		for (Entry<String, String> entry : fieldMap.entrySet()) {
			enFields[count] = entry.getKey();
			cnFields[count] = entry.getValue();
			count++;
		}

		// 在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
		SXSSFRow row = (SXSSFRow) sheet.createRow((int) 0);

		// 填充表头
		for (int i = 0; i < cnFields.length; i++) {
			SXSSFCell cell = (SXSSFCell) row.createCell(i);
			cell.setCellValue(cnFields[i]);
			cell.setCellStyle(style);
			sheet.setColumnWidth(i, cnFields[i].length() * 800);
		}

		// 填充内容
		for (int index = 0; index < list.size(); index++) {
			row = (SXSSFRow) sheet.createRow(index + 1);
			// 获取单个对象
			T item = list.get(index);
			for (int i = 0; i < enFields.length; i++) {
				Object objValue = getFieldValueByNameSequence(enFields[i], item);
				String fieldValue = "";
				if(objValue != null) {
					fieldValue = "";
					if(objValue instanceof Date) {
						fieldValue = DateUtils.parseDateString(String.valueOf(objValue), "yyyy-MM-dd HH:mm:ss");						
					} else {
						//若字段为state时,格式化state,设置下拉选框
						if("state".equals(enFields[i])) {
							fieldValue = formatState(Integer.parseInt((String) objValue));
							//设置认证状态那列为下拉选框
							String[] state = {"审核中","审核成功","审核失败"};
							XSSFDataValidationHelper dvHelper = new XSSFDataValidationHelper((XSSFSheet)sheet);
					        XSSFDataValidationConstraint dvConstraint1 = (XSSFDataValidationConstraint) dvHelper.createExplicitListConstraint(state);
					        CellRangeAddressList addressList = new CellRangeAddressList(1, list.size(), i,i);
					        XSSFDataValidation dataValidation = (XSSFDataValidation) dvHelper.createValidation(dvConstraint1,addressList);
					        sheet.addValidationData(dataValidation);
						} else {							
							fieldValue = objValue.toString();
						}
					}
				}
				row.setZeroHeight(false);
				row.setHeight((short) 1000);
				SXSSFCell cell = (SXSSFCell) row.createCell(i);
				//设置单元格格式为文本格式
				style.setDataFormat(format.getFormat("@"));
				cell.setCellStyle(style);
//				cell.setCellType(XSSFCell.CELL_TYPE_STRING);
				cell.setCellType(CellType.STRING);
				cell.setCellValue(fieldValue);
			}
		}		
	}
	
	/**
	 * 格式化认证状态
	 * @param state
	 * @return
	 */
	public static String formatState(Integer state) {
		switch (state) {
		case 4:
			return "审核成功";
		case 5:
			return "审核失败";
		default:
			return "审核中";
		}
	}
}